import axios from 'axios';
import dataVi from '../packages/DataVi';
import ajax from "@/examples/ajax";

const server = "http://localhost:8602/api/";

let autoLoginTimer;

function autoLogin() {
    ajax({
        type: "POST",
        url: server + "Account/Login",
        dataType: "json",
        data: {
            "userName": "admin",
            "password": "e10adc3949ba59abbe56e057f20f883e"
        },
        success: function (msg) {
            let data = {
                token: msg.Body.AccessToken,
                time: new Date()
            };
            let str = JSON.stringify(data);
            window.localStorage.setItem("dv_token", str);
        },
        error: function () {
            console.log("error")
        }
    })
}

function delayCallLogin() {
    if (autoLoginTimer) clearTimeout(autoLoginTimer);
    autoLoginTimer = setTimeout(() => {
        autoLogin()
    }, 1000);
}

function getToken() {
    let tokenInfo = window.localStorage.getItem("dv_token");
    if (tokenInfo) {
        let token = JSON.parse(tokenInfo);
        let tokenTime = new Date(token.time);
        if ((new Date().getTime() - tokenTime.getTime()) > 1000 * 60 * 60 * 12) {
            window.localStorage.clear();
            delayCallLogin();
        }
        return token.token;
    } else {
        delayCallLogin();
    }
    return "pd3eKmSng2EP7HCN5ERGUPMB34MbfflDFVpeRr4shtUYQv14EopAXQHxvGnSFv1XIEqDlWTciwSa9X5Rjj+aSqCR+jtF2VXP8zggwbAD2nigIE2cU3wuNdm6kg9rHOFRZhkKVlSSha4=";
}

function requestor() {
    this.invoke = function (data, api, acc, err) {
        try {
            let server = this.apiUrl();

            axios.post(`${server}${api}`, data)
                .then(d => {
                    if (d.data.ReturnCode == 200) {
                        acc(d.data.Body);
                    } else {
                        err({
                            code: d.data.ReturnCode,
                            msg: d.data.Message
                        });
                    }
                }).catch(e => {
                err({
                    code: 500,
                    msg: e
                });
            });
        } catch (e) {
            err({
                code: 500,
                msg: e
            });
        }
    }

    this.apiUrl = function () {
        return server;
    }
}

export function configAxios() {
    dataVi.useRequestor(new requestor());

    //axios.defaults.baseURL = defaultSettings.apiUrl;
    axios.interceptors.request.use(config => {
        var token = getToken();
        if (token) {
            config.headers['A-Token'] = getToken();
        }
        return config;
    }, error => {
        return Promise.reject(error);
    });
    axios.interceptors.response.use(
        response => {
            const returnObj = response.data;
            if (returnObj && returnObj.ReturnCode) {
                switch (returnObj.ReturnCode) {
                    case 200:
                        return Promise.resolve(response);
                    default:
                        return Promise.resolve(response);
                }
            } else {
                return Promise.reject();
            }
        });
}